<script  setup>
import { fileInputPromise } from '@/lib/xlsx/fileInputPromise'
import { fixPrecisionLossTime } from '@/lib/xlsx/fixPrecisionLossTime'
import dayjs from 'dayjs'
import VChart from 'vue-echarts'
import { utils, writeFile } from 'xlsx'
import 'echarts'

const data = [
  { stcd: '40516800', stnm: '红山口（三）', group: '黄河干流Ⅵ', river: '红山口沟' },
  { stcd: '30704390', stnm: '丰镇（饮三）', group: '永定河水系', river: '饮马河' },
  { stcd: '40516200', stnm: '美岱（大二）', group: '黄河干流Ⅵ', river: '大黑河' },
  { stcd: '20308000', stnm: '梅林庙（二）', group: '辽河干流水系', river: '乌力吉木仁河' },
  { stcd: '40515500', stnm: '东园（四）', group: '黄河干流Ⅴ', river: '五当沟' },
  { stcd: '1718900', stnm: '百灵庙（四）', group: '内蒙古内流区', river: '艾不盖河' },
  { stcd: '20310500', stnm: '白音他拉', group: '辽河干流水系', river: '黑木林河' },
  { stcd: '20213000', stnm: '乌丹（四）', group: '辽河干流水系', river: '少冷河' },
  { stcd: '11300301', stnm: '文得根', group: '嫩江', river: '绰尔河' },
  { stcd: '20205510', stnm: '台河口（西五）', group: '辽河干流水系', river: '西拉木伦河' },
  { stcd: '20115700', stnm: '新井', group: '辽河干流水系', river: '召苏河' },
  { stcd: '20116590', stnm: '哈拉道口', group: '辽河干流水系', river: '羊肠子河' },
  { stcd: '40514300', stnm: '塔尔湾（二）', group: '黄河干流Ⅴ', river: '昆都仑河' },
  { stcd: '20208000', stnm: '万合永', group: '辽河干流水系', river: '百岔河' },
  { stcd: '40517100', stnm: '店上村（三）', group: '黄河干流Ⅵ', river: '水磨沟' },
  { stcd: '1717100', stnm: '活福滩（二）', group: '内蒙古内流区', river: '乌兰花河' },
  { stcd: '40701050', stnm: '转龙湾', group: '黄河干流Ⅵ', river: '窟野河' },
  { stcd: '20114200', stnm: '杨树湾子（三）', group: '辽河干流水系', river: '西路嘎河' },
  { stcd: '20113001', stnm: '锦山（三）', group: '辽河干流水系', river: '锡伯河' },
  { stcd: '11420050', stnm: '索伦', group: '嫩江', river: '洮儿河' },
  { stcd: 'NM000001', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000002', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000003', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000004', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000005', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000006', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000007', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000008', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000009', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000010', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000011', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000012', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000013', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000014', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000015', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000016', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000017', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000018', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000019', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000020', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000021', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000024', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000025', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000026', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000027', stnm: '-', group: '-', river: '-' },
  { stcd: 'NM000028', stnm: '-', group: '-', river: '-' }
]
const time = ref(dayjs('2024-07-01').hour(9).startOf('hour').format('YYYY-MM-DD HH:mm:ss'))
const currentStcd = ref(data[0].stcd)
const aiResult = ref()

function currentChange(row) {
  currentStcd.value = row.stcd
  aiResult.value = undefined
}

const option = toRef(() => ({
  xAxis: {
    type: 'category'
  },
  yAxis: {
    type: 'value',
    name: '雨量(mm/3h)'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {},
  dataset: {
    dimensions: ['time', 'streamflow'],
    source: toValue(aiResult) ?? []
  },
  series: [
    {
      type: 'line',
      name: '流量'
    }
  ]
}))

function downloadTemplate() {
  const excelData = [
    ['时间', '雨量'],
    ['2024-07-01 09:00:00', 10.5],
    ['2024-07-01 12:00:00', 15.5],
    ['2024-07-01 15:00:00', 9.5]
  ]
  const wb = utils.book_new()
  const ws = utils.aoa_to_sheet(excelData)
  utils.book_append_sheet(wb, ws, 'Sheet1')
  writeFile(wb, '数据模板.xlsx')
}
const isLoading = ref(false)
async function onImportExcel() {
  const startTime = dayjs(time.value).utc().format('YYYY-MM-DD-HH')
  const { data } = await fileInputPromise({ header: ['tm', 'rain'] })
  const excelData = data.map((item) => {
    const dt = fixPrecisionLossTime(item.tm)
    return {
      ...item,
      tm: dayjs(dt).utc().format('YYYY-MM-DDTHH:mm:ss')
    }
  })
  isLoading.value = true
  fetch('/model_infer/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      startTime,
      basinId: currentStcd.value,
      rainList: excelData
    })
  }).then(res => res.json()).then((res) => {
    aiResult.value = res.map((item) => {
      return {
        ...item,
        time: dayjs(item.time).add(8, 'hour').format('YYYY-MM-DD HH:mm:ss')
      }
    })
  }).finally(() => {
    isLoading.value = false
  })
}
</script>

<template>
  <div class="h-full flex p-4 space-x-4">
    <div class="flex flex-col">
      <el-table row-key="stcd" :data="data" border highlight-current-row :current-row-key="currentStcd" @current-change="currentChange">
        <el-table-column prop="stcd" label="编码" width="100" />
        <el-table-column prop="stnm" label="水文站名称" width="130" />
        <el-table-column prop="group" label="集群名" width="130" />
        <el-table-column prop="river" label="河流名" width="130" />
      </el-table>
    </div>
    <div class="flex-1 flex flex-col space-y-4">
      <div class="flex items-center space-x-4">
        <el-date-picker v-model="time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        <el-button type="primary" @click="onImportExcel">
          上传数据
        </el-button>
        <el-button type="primary" @click="downloadTemplate">
          下载模板
        </el-button>
      </div>
      <div v-loading="isLoading" class="flex-1 relative">
        <VChart v-if="aiResult" autoresize class="absolute inset-0" :option="option" />
        <el-empty v-else-if="!isLoading" description="请上传数据" />
      </div>
    </div>
  </div>
</template>
